using System;
using System.Collections.Generic;
using System.Text;
using BizTalkCop.Rules.Bases;
using Microsoft.FxCop.Sdk;
using Microsoft.XLANGs.BaseTypes;

namespace BizTalkCop.Rules.Naming.Rules
{
    /// <summary>
    /// Rule verifying that schemas are named with their root node name
    /// </summary>
    public class SchemaNamesShouldIndicateRootNode : ConfiguredRuleBase
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        public SchemaNamesShouldIndicateRootNode() : base("SchemaNamesShouldIndicateRootNode") { }

        /// <summary>
        /// Checks if the schema name is correctly started with the root node
        /// </summary>
        /// <param name="type">Type to check</param>
        /// <returns>Problem collection</returns>
        public override ProblemCollection Check(TypeNode type)
        {
            if (IsDocumentSchema(type))
            {
                string separator = this.GetConfiguredSetting(Setting.Separator);
                string[] nameParts = type.Name.Name.Split(separator.ToCharArray());
                //check the first part:
                string rootNode = GetAttributeArgument<SchemaAttribute>(type, 1);
                if (nameParts[0] != rootNode)
                {
                    Problems.Add(new Problem(GetNamedResolution("RootNode", nameParts[0], rootNode), type));
                }
            }
            return Problems;
        }

        #region Configured settings

        static SchemaNamesShouldIndicateRootNode()
        {
            Dictionary<string, string> defaults = new Dictionary<string, string>();
            defaults.Add(Setting.Separator, Default.Separator);
            SetDefaults(typeof(SchemaNamesShouldIndicateRootNode), defaults);
        }

        private struct Setting
        {
            public const string Separator = "Separator";
        }

        private struct Default
        {
            public const string Separator = "_";
        }

        #endregion
    }
}
